package com.neuedu.corejava.ch13.homework;


/**
 * 线程同步的实例：可能有多个线程对统一资源进行访问
 * @author admin
 *
 */

public class HomeWork1 {
	
	
	private int count =0;
	
	public synchronized void add(int threadId) {
		count++;
		System.out.println(threadId +","+count);
		
	}
	
	public synchronized void desc(int threadId) {
		count--;
		System.out.println(threadId + " ," + count);
	}
	
	class AddClass implements Runnable{
		
		private int threadId =0;
		
		public AddClass(int id) {
			this.threadId=id;
		}
		
		@Override
		public void run() {
			for(int i=0;i<50;i++) {
				add(threadId);
				
//				try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
			
			
		}
		
	}
	
	class DescClass implements Runnable {
		private int threadId = 0;

		public DescClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				desc(threadId);
				
//				try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//				}
			}
		}
	}


	public static void main(String[] args) {
		HomeWork1 homeWork1 = new HomeWork1();
		AddClass addClass1 =homeWork1. new AddClass(1);
		AddClass addClass2 =homeWork1. new AddClass(2);
		DescClass descClass1 =homeWork1.new DescClass(3);
		DescClass descClass2 = homeWork1.new DescClass(4);
		
		new Thread(addClass1).start();
		new Thread(addClass2).start();
		new Thread(descClass1).start();
		new Thread(descClass2).start();
		
		
		
		

	}

}
